package ltd.controller;

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.googlecode.genericdao.search.Search;
import ltd.bean.*;
import ltd.constant.ConfigConstant;
import ltd.constant.Constant;
import ltd.entity.GameMsg;
import ltd.entity.Layout;
import ltd.entity.Simulator;
import ltd.entity.Video;
import ltd.help.ConfigHelper;
import ltd.service.SimulatorService;
import ltd.util.JsonUtil;
import ltd.util.StringUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;


/**
 * 检查各种版本的API
 *
 * Created by chinalin on 2017/4/11.
 */

@Controller
@RequestMapping("/checkver/*")
public class CheckController {
    @Resource(name = "simulatorService")
    private SimulatorService simulatorService ;
    private static Logger LOGGER = LoggerFactory.getLogger(CheckController.class) ;
    @Resource
    private SessionFactory sessionFactory;

/*    @ModelAttribute
    @RequestMapping(value = "bootver",method = RequestMethod.POST)
//    @RequestMapping(value = "bootver",method = RequestMethod.GET)
    public void checkBootVer(@RequestParam int type , @RequestParam int version, HttpServletResponse response) throws IOException {

        Search search = new Search(Simulator.class);
        search.addFilterEqual("type", type);
        Simulator simulator = simulatorService.searchOne(search);
        if (simulator != null){
            int bootVerDS = simulator.getBootver() ;
            String bootNameDs = simulator.getBootname() ;
            compareVer(response, bootVerDS, version, bootNameDs,ConfigConstant.TAG_BOOT);
        }else {
            sendError(response,"请求错误,错误的type:" + type);
        }
    }*/

    /**
     * return: 1: ResultCode
     *         2: boot图片链接地址
     */
    @ModelAttribute
    @RequestMapping(value = "bootver",method = RequestMethod.POST)
    public void checkBootVer(@RequestParam int type , HttpServletResponse response) throws IOException {

        Search search = new Search(Simulator.class);
        search.addFilterEqual("type", type);
        Simulator simulator = simulatorService.searchOne(search);
        if (simulator != null){
//            int bootVerDS = simulator.getBootver() ;
            String bootNameDs = simulator.getBootname() ;
            if (StringUtil.isEmpty(bootNameDs)){
                sendError(response,"boot图片为空");
            }else {
                MSGResult msgres = new MSGResult();
                msgres.setResultCode(ConfigConstant.RESULT_CODE_UPDATE);
                String BootPicUrl = Constant.DOWNLOAD_LINK + bootNameDs ;
                msgres.setData( BootPicUrl );
                writeJson(response,msgres);
            }
            LOGGER.error("bootver传输完成");
//            compareVer(response, bootVerDS, version, bootNameDs,ConfigConstant.TAG_BOOT);
        }else {
            sendError(response,"请求错误,错误的type:" + type);
        }
    }


    /**
     * return: 1: ResultCode
     *         2: bg图片链接地址
     */
    @ModelAttribute
    @RequestMapping(value = "bgver",method = RequestMethod.POST)
    public void checkBgVer(@RequestParam int type , HttpServletResponse response) throws IOException {
//        public void checkBgVer(@RequestParam int type , @RequestParam int version, HttpServletResponse response) throws IOException {
        Search search = new Search(Simulator.class) ;
        search.addFilterEqual("type", type) ;
        Simulator simulator = simulatorService.searchOne(search) ;
        if (simulator != null){
//            int bgverDS = simulator.getBgver() ;
            String bgnameDS = simulator.getBgname() ;
            if (StringUtil.isEmpty(bgnameDS)){
                sendError(response,"bg图片为空");
            }else {
                MSGResult msgres = new MSGResult();
                msgres.setResultCode(ConfigConstant.RESULT_CODE_UPDATE);
                String BgPicUrl = Constant.DOWNLOAD_LINK + bgnameDS ;
                msgres.setData( BgPicUrl );
                writeJson(response,msgres);
            }
//            compareVer(response, bgverDS, version, bgnameDS,ConfigConstant.TAG_BGVER) ;
            LOGGER.error("bgpic传输完成");
        }else {
            sendError(response,"请求错误,错误的type:" + type);
        }
    }

    @ModelAttribute
    @RequestMapping("gametablever")
//    @RequestMapping(value = "gametablever",method = RequestMethod.POST)
    public void checkGameTableVer(@RequestParam int type , @RequestParam int version, HttpServletResponse response) throws IOException {
//=======================================读取layout写入文件
/*        Session session1 = sessionFactory.openSession();
        List<Layout> list =  (List<Layout>) session1.createSQLQuery( " select * from  " + "layout691" ).addEntity(Layout.class ).list();
        session1.close();
        LayoutMSGList layoutMSGList = new LayoutMSGList() ;
        layoutMSGList.setList(list);
        String json = JsonUtil.toJson(layoutMSGList) ;
        String fileName = "F:\\layout.txt" ;
        FileUtil.writeStringToFile(json,fileName);*/
//=======================================
        Search search = new Search(Simulator.class) ;
        search.addFilterEqual("type", type) ;
        Simulator simulator = simulatorService.searchOne(search) ;
        if (simulator != null){
            int gametableverDS = simulator.getGametablever() ;
            String gametablenameDS = simulator.getGametablename() ;
            compareGameTableVer(response, gametableverDS, version, gametablenameDS) ;
        }else {
            sendError(response,"请求错误,错误的type:" + type);
        }
    }

    /**
     * return: 1: ResultCode 2:root -->
     *      2.0: tag,信息头，表示回复哪个请求
     *      2.1: version:版本号
     *      2.2: layoutMSGList  读出的布局表的数据
     *      2.3: message 回复的提示信息
     */
    @ModelAttribute
//    @RequestMapping("layoutver")
    @RequestMapping(value = "layoutver",method = RequestMethod.POST)
    public void checkLayoutVer(@RequestParam int type , @RequestParam int version, HttpServletResponse response) throws IOException {
        Search search = new Search(Simulator.class) ;
        search.addFilterEqual("type", type) ;
        Simulator simulator = simulatorService.searchOne(search) ;
        if (simulator != null){
            MSGResult msgres = new MSGResult();
            int layoutVerDS = simulator.getLayoutver() ;
            if (layoutVerDS > version){
                //版本高，要升级
                msgres.setResultCode(ConfigConstant.RESULT_CODE_UPDATE);
//=======================================读取layout数据库
                String layoutNameDS = simulator.getLayoutname() ;
                Session session = sessionFactory.openSession();
                List<Layout> list =  (List<Layout>) session.createSQLQuery( " select * from  " + layoutNameDS ).addEntity(Layout.class ).list();
                session.close();
                LayoutMSGList layoutMSGList = new LayoutMSGList() ;
                layoutMSGList.setList(list);
//                String json = JsonUtil.toJson(layoutMSGList) ;
//                msgres.setData(json);
                ObjectNode root = JacksonMapper.getMapper().createObjectNode();
                root.put("tag",ConfigConstant.TAG_LAYOUTVER) ;
                root.put("version", layoutVerDS);
                root.put("layoutMSGList", JsonUtil.toJson(layoutMSGList));
                root.put("picurl", ConfigHelper.getDownloadLink() + layoutNameDS + "/") ; //图片地址为download再加上 layout布局表同名的文件夹
                root.put("message", Constant.VERSION_UPDATE);
                msgres.setData(root.toString());
//=======================================
            }else {
                //不用升级
                msgres.setResultCode(ConfigConstant.RESULT_CODE_NOUPDATE);
                msgres.setData(Constant.VERSION_LATEST);
            }
            writeJson(response,msgres);
            LOGGER.error("Layout传输完成");

//            int layoutVerDS = simulator.getLayoutver() ;
//            String layoutNameDS = simulator.getLayoutname() ;
//            compareVer(response, layoutVerDS, version, layoutNameDS,ConfigConstant.TAG_LAYOUTVER) ;
        }else {
            sendError(response,"请求错误,错误的type:" + type);
        }
    }

    @ModelAttribute
//    @RequestMapping("versioncode")
    @RequestMapping(value = "versioncode",method = RequestMethod.POST)
    public void checkVersionCode(@RequestParam int type , @RequestParam int version, HttpServletResponse response) throws IOException {

        Search search = new Search(Simulator.class) ;
        search.addFilterEqual("type", type) ;
        Simulator simulator = simulatorService.searchOne(search) ;
        if (simulator != null){
            int versionCodeDS = simulator.getVersioncode() ;
            String versionName = simulator.getVersionname() ;
            String downloadLink = Constant.DOWNLOAD_LINK;
            downloadLink += Constant.APK_NAME + type + ".apk" ;
            compareVer(response,versionCodeDS, version,downloadLink,versionName,ConfigConstant.TAG_VERSIONCODE);
        }else {
            sendError(response,"请求错误,错误的type:" + type);
        }
    }

    /**
     * return: 1: ResultCode 2:root -->
     *      2.0: tag,信息头，表示回复哪个请求
     *      2.1: videoList:video的数据表
     *      2.2: downloadLink下载地址，需加上video名字合成最终下载地址
     *      2.3: message 回复的提示信息
     */
    @ModelAttribute
    @RequestMapping(value = "getvideo",method = RequestMethod.POST)
    public void getVideo(@RequestParam int type , HttpServletResponse response) throws IOException {
        MSGResult msgres = new MSGResult();
        Search search = new Search(Simulator.class) ;
        search.addFilterEqual("type", type) ;
        Simulator simulator = simulatorService.searchOne(search) ;
        if (simulator != null){
                    String videoNameDS = simulator.getVideoname() ;     //视频文件数据表名
                    if (videoNameDS ==null || videoNameDS.equals("")){
                        //无视频文件
                        msgres.setResultCode(ConfigConstant.RESULT_CODE_NO_VEDIO);
                        msgres.setData(Constant.NO_VIDEO);
                    }else {
                        Session session = sessionFactory.openSession();
                        List<Video> list =  (List<Video>) session.createSQLQuery( " select * from  " + videoNameDS).addEntity(Video.class ).list();
                        session.close();

                        VideoList videoList = new VideoList();
                        videoList.setList(list);

                        msgres.setResultCode(ConfigConstant.RESULT_CODE_FIND_VEDIO);
                        ObjectNode root = JacksonMapper.getMapper().createObjectNode();
//                        String videoList = JsonUtil.toJson(videoList);
                        root.put("tag",ConfigConstant.TAG_GETVIDEO) ;
                        root.put("videoList", JsonUtil.toJson(videoList));
                        root.put("downloadLink", Constant.DOWNLOAD_LINK);
                        root.put("message", "找到视频文件");
                        msgres.setData(root.toString());

//                        GetVideoData<List> getVideoData = new GetVideoData<>();
//                        getVideoData.setDownloadlink(Constant.DOWNLOAD_LINK);
//                        getVideoData.setData(list);
//                        msgres.setData(getVideoData);
                    }
            writeJson(response,msgres);
        }else {
            sendError(response,"请求错误,错误的type:" + type);
        }
    }

    private void compareVer(HttpServletResponse response,int verDS,int ver,String nameDS,int resTag) throws IOException{
        String downloadLink = Constant.DOWNLOAD_LINK;
        downloadLink += nameDS ;
        compareVer(response,verDS,ver,downloadLink,Constant.VERSION_UPDATE,resTag);
    }

    /**
     * return: 1: ResultCode 2:root -->
     *      2.0: tag,信息头，表示回复哪个请求
     *      2.1: version:版本号
     *      2.2: downloadLink  完整的下载地址
     *      2.3: message 回复的提示信息
     */
    private void compareVer(HttpServletResponse response,int verDS,int ver,String downloadLink,String message,int resTag) throws IOException{
        MSGResult msgres = new MSGResult();
        if (verDS > ver){
            //版本高，要升级
            msgres.setResultCode(ConfigConstant.RESULT_CODE_UPDATE);
//            msgres.setResultMessage( message);

            ObjectNode root = JacksonMapper.getMapper().createObjectNode();
            root.put("tag",resTag) ;
            root.put("version", verDS);
            root.put("downloadLink", downloadLink);
            root.put("message", message);

            msgres.setData(root.toString());

//            CheckVerData<String> msgData = new CheckVerData<>();
//            msgData.setVersion(verDS);
//            msgData.setData(downloadLink);
//            msgres.setData( msgData);

        }else {
            //不用升级
            msgres.setResultCode(ConfigConstant.RESULT_CODE_NOUPDATE);
            msgres.setData(Constant.VERSION_LATEST);
        }
        writeJson(response,msgres);
        LOGGER.error("compareVer传输完成");
    }

    /**
     * return: 1: ResultCode 2:root -->
     *      2.0: tag,信息头，表示回复哪个请求
     *      2.1: version:版本号
     *      2.2: gameMsgList  读出的游戏推荐表的数据
     *      2.3: message 回复的提示信息
     */
    private void compareGameTableVer(HttpServletResponse response,int verDS,int ver,String nameDS) throws IOException{
        MSGResult msgres = new MSGResult();
        if (verDS > ver){
            //版本高，要升级
            Session session = sessionFactory.openSession();
            List<GameMsg> list =  (List<GameMsg>) session.createSQLQuery( " select * from  " + nameDS ).addEntity(GameMsg.class ).list();
            session.close();

            GameMsgList gameMsgList = new GameMsgList() ;
            gameMsgList.setList(list);

            msgres.setResultCode(ConfigConstant.RESULT_CODE_UPDATE);
            ObjectNode root = JacksonMapper.getMapper().createObjectNode();
//            String gameMsgListS = JsonUtil.toJson(gameMsgList);
            root.put("tag",ConfigConstant.TAG_GAMETABLE) ;
            root.put("version", verDS);
            root.put("gameMsgList", JsonUtil.toJson(gameMsgList));
            root.put("message", Constant.VERSION_UPDATE);
            msgres.setData(root.toString());

        }else {
            //不用升级
            msgres.setResultCode(ConfigConstant.RESULT_CODE_NOUPDATE);
            msgres.setData(Constant.VERSION_LATEST);
        }
        writeJson(response,msgres);
    }

    private void sendError(HttpServletResponse response,String err) throws IOException{
        MSGResult msgres = new MSGResult();
        msgres.setResultCode(ConfigConstant.RESULT_CODE_ERROR);
        msgres.setData(err);
//        msgres.setData("");
        writeJson(response,msgres);
    }

    private void writeJson(HttpServletResponse response,MSGResult msgres) throws IOException{
        try {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter() ;
            String json = JsonUtil.toJson(msgres) ;
            writer.write(json);
            writer.flush();
            writer.close();
        }catch (IOException e){
            LOGGER.error("response getWriter failure :" + e);
            throw new RuntimeException(e) ;
        }
    }
}
